<template>
  <view class="component-box">
    <view
      class="classify-section"
      :style="[classifyCss]"
      :class="styleType == 2 ? 'flex-layout' : ''"
      v-if="classifyList.length"
    >
      <div class="left-hold-place" v-if="styleType == 2">
        <div
          class="tab-item"
          v-for="(item, index) in classifyList"
          :key="index"
        ></div>
      </div>
      <view class="classify-header" :style="[goodsTabCss]">
        <view :style="[moduleBgCss]" class="module-bg"></view>
        <u-sticky :offset-top="stickyOffTop" :h5-nav-height="0">
          <view :style="{ backgroundColor: moduleBgCss.backgroundColor }">
            <!-- 默认样式tab -->
            <defaultTab
              v-if="styleType == 1 && tabStyle == 1"
              :classifyList="classifyList"
              :activeTab="activeTab"
              :propsData="propsData"
              @changeTab="changeTab"
            ></defaultTab>
            <!-- 带副标题的tab -->
            <subtitleTab
              v-if="styleType == 1 && (tabStyle == 2 || tabStyle == 3)"
              :classifyList="classifyList"
              :activeTab="activeTab"
              :propsData="propsData"
              @changeTab="changeTab"
            ></subtitleTab>
            <!-- 左侧tab -->
            <leftTab
              v-if="styleType == 2"
              :classifyList="classifyList"
              :activeTab="activeTab"
              :propsData="propsData"
              @changeTab="changeTab"
            ></leftTab>
          </view>
        </u-sticky>
      </view>
      <view class="classify-body" :style="[goodsListCss]">
        <view :style="[goodsBgCss]" class="module-bg"></view>
        <!-- 样式1 -->

        <!-- 样式3 -->
        <columnTem
          v-if="goodsType == 3"
          :propsData="propsData"
          :goodsList="goodsList"
          :goodsItemSpace="goodsItemSpace"
          @clickBuyBtn="clickBuyBtn"
          @toGoodDetail="toGoodDetail"
        ></columnTem>
        <defaultTem
          v-else
          :propsData="propsData"
          :goodsList="goodsList"
          :goodsItemSpace="goodsItemSpace"
          @clickBuyBtn="clickBuyBtn"
          @toGoodDetail="toGoodDetail"
        ></defaultTem>
      </view>
    </view>

    <!-- 底部按钮 -->
    <footBtn
      :cartSelectData="cartSelectData"
      :cartTotalPrice="cartTotalPrice"
      :cartChoosedNum="cartChoosedNum"
      @handleFoot="handleFoot"
      @handleFootBtn="handleFootBtn"
    ></footBtn>

    <!-- 已选商品弹窗 -->
    <choosedPopup
      :listData="cartSelectData"
      v-if="showChoosePopup"
      @closePopup="showChoosePopup = false"
      @clearChoosed="clearChoosed"
      @selectAddOne="selectAddOne"
      @selectReduceOne="selectReduceOne"
    ></choosedPopup>

    <!-- sku弹框 -->
    <newSkuPopup
      ref="sku-popup"
      :skuData="{}"
      :goodsInfo="cartGoodInfo"
      :foodExtGoods="food_ext_goods"
      :foodExtGoodsName="food_ext_goods_name"
      @confirm="(e) => setAddgoodsToCart(e.data)"
      @closeSkuPopup="showSkuPopup = !showSkuPopup"
    ></newSkuPopup>
  </view>
</template>

<script>
import { diyMixin } from "../mixins/diy";
import goodsAddCart from "../goodsAddCart/index.vue";
import defaultTem from "./templates/defaultTem.vue";
import flexTwoTem from "../productShow/templates/flexTwo.vue";
import columnTem from "./templates/column.vue";
import flexGroupTem from "../productShow/templates/flexGroup.vue";
import defaultTab from "./templates/defalut.vue";
import subtitleTab from "./templates/subtitleTab.vue";
import leftTab from "./templates/leftTab.vue";

import footBtn from "./components/footBtn.vue";
import newSkuPopup from "./components/newSkuPopup.vue";
import choosedPopup from "./components/choosedPopup.vue";
import { orderMealMixin } from "../mixins/index";

export default {
  props: {
    propsData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    loadMoreProductClassify: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    defaultTem,
    flexTwoTem,
    columnTem,
    flexGroupTem,
    goodsAddCart,
    defaultTab,
    subtitleTab,
    leftTab,

    footBtn,
    newSkuPopup,
    choosedPopup,
  },
  mixins: [diyMixin, orderMealMixin], //混入文件
  watch: {
    loadMoreProductClassify(val) {
      if (val) {
        this.scrollToEnd();
      }
    },

    cartSelectData(val) {
      this.updateDataToView();
    },
  },
  data() {
    return {
      activeTab: 0,
      goodsList: [],
      goodsOfAdd: {}, // 添加到购物车的商品
      currentTab: {},
      selectArr: [],
      page: 1,
      pageSize: 10,
      row_count: 0,
      classifyList: [],

      skuData: [],
      showChoosePopup: false,
      cartGoodInfo: null,

      food_ext_goods: "",
      food_ext_goods_name: "",
    };
  },
  computed: {
    styleType() {
      return this.propsData.params.styleType;
    },
    goodsType() {
      return this.propsData.params.goodsType;
    },
    type() {
      return this.propsData.params.type;
    },
    goodsItemSpace() {
      let out = this.propsData.params.goodsItemOutSpace || "0";
      let inner = this.propsData.params.goodsItemInnerSpace || "0";
      let goodsType = this.propsData.params.goodsType || 1;
      let css = {};
      out = out * 2;
      inner = inner * 2;
      if (out) {
        if (goodsType == 1) {
          css["margin"] = `0 0 ${out}rpx 0`;
        }
        if (goodsType == 3) {
          css["margin"] = `0 ${out}rpx ${out}rpx ${out}rpx`;
        }
        if (goodsType == 2 || goodsType == 4) {
          css["margin"] = `0 ${out}rpx ${out}rpx 0`;
        }
      }
      if (inner) {
        css["padding"] = `${inner}rpx`;
      }
      return css;
    },
    stickyOffTop() {
      let top = 0;
      top = this.statusBarHeight * 2 + 88 - 4;
      return top.toString();
    },
    tabStyle() {
      return this.propsData.params.tabStyle || "1";
    },
    tabSectionBg() {
      if (this.styleType == 2)
        return { backgroundColor: this.propsData.params.leftTabBg };
      return "";
    },
    goodsTabCss() {
      if (!this.propsData) return {};
      let style = Object.assign({}, this.propsData.moduleCss);
      if (style.margin) style.margin = `0 0 ${style.margin * 2}rpx 0`;
      if (style.padding) style.padding = `0 ${style.padding * 2}rpx`;
      if (style.borderRadius)
        style["borderRadius"] = `${style.borderRadius * 2}rpx`;
      let obj = {
        margin: style.margin,
        borderRadius: style.borderRadius,
        padding: style.padding,
        position: "relative",
        overflow: "hidden",
      };
      if (this.styleType == 2) {
        obj["backgroundColor"] = this.propsData.params.leftTabBg;
      }
      return obj;
    },
    classifyCss() {
      if (!this.propsData.params?.goodsBgCss) return {};
      let style = Object.assign({}, this.propsData.params.goodsBgCss);
      if (style.borderRadius)
        style["borderRadius"] = `${style.borderRadius * 2}rpx`;
      let obj = {
        borderRadius: style.borderRadius,
        position: "relative",
        overflow: "hidden",
      };
      return obj;
    },
    goodsListCss() {
      if (!this.propsData.params?.goodsBgCss) return {};
      let style = Object.assign({}, this.propsData.params.goodsBgCss);
      if (style.margin) style.margin = `0 0 ${style.margin * 2}rpx 0`;
      if (style.padding) style.padding = `0 ${style.padding * 2}rpx`;
      // if (style.borderRadius)
      //   style["borderRadius"] = `${style.borderRadius * 2} rpx`;
      let obj = {
        margin: style.margin,
        borderRadius: style.borderRadius,
        padding: style.padding,
        position: "relative",
        overflow: "hidden",
      };
      return obj;
    },
    goodsBgCss() {
      if (!this.propsData.params?.goodsBgCss) return {};
      let style = Object.assign({}, this.propsData.params.goodsBgCss);
      // if (style.borderRadius)
      //   style["borderRadius"] = `${style.borderRadius * 2}rpx`;
      if (!style.useBackground) {
        return {
          background: "inherit",
        };
      }
      let hSpace = style.padding;
      if (hSpace) {
        style["width"] = `calc(100% - ${hSpace * 4}rpx)`;
        style["left"] = hSpace * 2 + "rpx";
      }
      return style;
    },
  },
  filters: {},
  onUnload() {
    clearInterval(this.intervalPoll);
  },
  mounted() {
    if (uni.getStorageSync("food_table_num")) {
      this.storeTableNum = uni.getStorageSync("food_table_num");
    }

    this.filterSelectData();

    // 以下新传出的
    if (!uni.getStorageSync("flag_id")) {
      this.storeFlagId = "";
    }

    clearInterval(this.intervalPoll);
    // 页面显示时，重新开始轮询
    this.pollingCartData();
    this.clearIntervalPoll = false;
    this.startPolling();
  },
  methods: {
    // 筛选出商品id数组
    async filterSelectData() {
      let { type } = this,
        classifyList = [];

      if (type === "2") {
        const res = await this.$allrequest.diy.getFoodsCatList();
        classifyList =
          res.data.list.map((el) => {
            el.dataFrom = "select";
            return el;
          }) || [];
      } else {
        classifyList = this.propsData.params.classifyList;
      }
      this.classifyList = classifyList;

      let [item] = this.classifyList.filter((d, index) => {
        return this.activeTab == index;
      });
      if (!item) return;
      this.currentTab = item;
      if (item && item.dataFrom == "select") {
        item.data.forEach((d) => {
          this.selectArr.push(d.id);
        });
      }

      this.initProductData();
    },
    // 初始化商品数据
    initProductData(type = "") {
      let params = {};
      if (this.currentTab.dataFrom == "classify") {
        params = {
          cat_id: this.currentTab.classifyId,
          page: this.page,
          limit: this.pageSize,
        };
      }
      if (this.currentTab.dataFrom == "select") {
        params = {
          goods_id: this.selectArr
            .slice((this.page - 1) * 10, this.page * 10)
            .join(","),
        };
      }
      if (type) {
        params["isLoadMore"] = true;
      }
      if (this.currentTab.dataFrom) {
        this.getProducts(params);
      }
    },
    // 开始轮询数据
    startPolling() {
      setTimeout(() => {
        this.intervalPollingCartData();
      }, 3000);
    },

    // api获取商品数据
    async getProducts(params) {
      const res = await this.$allrequest.diy.getFoodsList(params);
      if (res.code == 0) {
        if (this.currentTab.dataFrom == "classify") {
          this.row_count = res.data.row_count;
        }

        this.goodsList = res.data.goods;
      }
    },
    // 切换tab
    changeTab(e) {
      let { item, index } = e;
      this.activeTab = index;
      this.currentTab = item;
      this.selectArr = [];
      this.page = 1;
      this.goodsList = [];

      const query = uni.createSelectorQuery().in(this);
      query
        .select(".classify-header")
        .boundingClientRect((data) => {
          let top = 0;
          if (data.top <= 0) {
            top = 0;
          } else {
            top = data.top;
          }
          this.$emit("classifyToTop", { nodeTop: data.top });
        })
        .exec();

      this.filterSelectData();
    },
    // 点击添加购物车按钮回调
    clickBuyBtn({ item, type }) {
      switch (type) {
        case "add":
          if (item.use_attr === 0) {
            this.addOneToBuy(item);
          } else {
            this.actionSelectSku(item);
          }
          break;

        case "reduce":
          this.reduceOne(item);
          break;
      }
    },
    // 跳转商品详情
    toGoodDetail(e) {
      if (!e) return;
      let id = e.id;
      uni.navigateTo({
        url: "/alipay-order/goods/goods?id=" + id,
      });
    },
    scrollToEnd() {
      if (
        this.page * this.pageSize >= this.row_count &&
        this.currentTab.dataFrom == "classify"
      )
        return;

      if (
        this.currentTab.dataFrom == "select" &&
        this.page * this.pageSize >= this.selectArr.length
      )
        return;
      this.page++;
      this.initProductData("more");
    },
    // 同步点餐数据
    updateDataToView() {
      this.goodsList.forEach((k) => {
        k.select_num = 0;
        k.user_num = 0;
        k.other_num = 0;
        for (let i = 0; i < this.cartSelectData.length; i++) {
          for (let n = 0; n < this.cartSelectData[i].goods_list.length; n++) {
            if (
              this.user_id == this.cartSelectData[i].user_id &&
              k.id == this.cartSelectData[i].goods_list[n].goods_id
            ) {
              k.cart_id = this.cartSelectData[i].goods_list[n].cart_id;
              k.user_num =
                k.user_num + this.cartSelectData[i].goods_list[n].num;
            }

            if (
              this.user_id != this.cartSelectData[i].user_id &&
              k.id == this.cartSelectData[i].goods_list[n].goods_id
            ) {
              k.cart_id = this.cartSelectData[i].goods_list[n].cart_id;

              k.other_num =
                k.other_num + this.cartSelectData[i].goods_list[n].num;
            }
          }
        }
        k.select_num = k.user_num + k.other_num;
      });
    },

    // 清空用户所选商品
    clearUserChoosed(e) {
      let user_id = e.user_id;
      this.emptyUserCart(user_id, () => {
        this.showChoosePopup = false;
      });
    },

    // 清空购物车
    clearCartAll() {
      this.emptyCart(() => {
        this.showChoosePopup = false;
      });
    },

    // 已选弹框添加一个回调
    selectAddOne(e) {
      let item = JSON.parse(JSON.stringify(e.item));

      if (typeof item.food_ext_goods !== "string") {
        item.food_ext_goods = JSON.stringify(item.food_ext_goods);
      }

      let attr = item.attr_list;
      attr.forEach((d) => {
        d["attr_id"] = d.id;
      });
      let params = {
        attr: JSON.stringify(attr),
        num: 1,
        goods_id: item.goods_id,
        food_ext_goods: item.food_ext_goods,
      };
      this.addGoodsToCart(params, () => {
        this.pollingCartData(() => {
          this.updateDataToView();
        });
      });
    },

    // 已选弹框删除一个回调
    selectReduceOne(e) {
      this.reduceOneCartNum(e, () => {
        this.pollingCartData(() => {
          this.updateDataToView();
        });
      });
    },

    // 添加一个商品
    addOneToBuy(sku, item, i) {
      if (sku.num <= 0) {
        uni.showToast({
          title: this.$t("alipay.noCount"),
          icon: "none",
        });
        return;
      }

      let data = Object.assign({}, sku);
      let attr = sku.attr_group_list[0];
      attr = [
        {
          attr_group_id: attr.attr_group_id,
          attr_group_name: attr.attr_group_name,
          attr_id: attr.attr_list[0].attr_id,
          attr_name: attr.attr_list[0].attr_name,
        },
      ];
      let params = {
        attr: JSON.stringify(attr),
        num: 1,
        goods_id: sku.id || sku.goods_id,
      };

      if (sku.food_ext_goods) {
        this.food_ext_goods = sku.food_ext_goods;
        this.cartGoodInfo = sku;
        this.$refs["sku-popup"].showPopup(1, data);
      } else {
        this.food_ext_goods = "";
        this.setAddgoodsToCart(params);
      }
    },

    // 加入购物车
    setAddgoodsToCart(params) {
      this.addGoodsToCart(params, () => {
        this.showSkuPopup = false;
        this.food_ext_goods = "";
        this.food_ext_goods_name = "";
        this.cartGoodInfo = null;
        this.$refs["sku-popup"].closePopup();
        this.pollingCartData(() => {
          this.updateDataToView();
        });
      });
    },

    // 删除一个商品
    reduceOne(item) {
      if (item.select_num <= 0) return;
      if (item.user_num <= 0) return;
      item.select_num--;
      item.user_num--;
      if (item.num <= 0) {
        item.num = 0;
      }
      let params = {
        cart_id: item.cart_id,
        num: this.storeTableNum ? item.user_num : item.select_num,
      };
      this.reduceOneCartNum(params, () => {
        this.pollingCartData(() => {
          this.updateDataToView();
        });
      });
    },

    // 点击选择规格
    actionSelectSku(sku, item) {
      this.cartGoodInfo = sku;
      this.skuInfo = sku;
      this.food_ext_goods = sku.food_ext_goods;
      this.food_ext_goods_name = sku.food_ext_goods_model
        ? sku.food_ext_goods_model.name
        : "";
      this.$refs["sku-popup"].showPopup();
    },

    selectAccessories(food_ext_goods) {
      this.params.food_ext_goods = food_ext_goods.length
        ? JSON.stringify(food_ext_goods)
        : "";
      this.setAddgoodsToCart();
    },

    // 点击页面底部，弹出已选sku弹框
    handleFoot() {
      this.showChoosePopup = !this.showChoosePopup;
    },

    // 点击底部按钮组件回调。去结算
    handleFootBtn() {
      uni.showToast({
        title: this.$t("home.loading"),
        duration: 2000,
        icon: "none",
      });

      // 好友拼单
      if (
        this.storeFlagId &&
        !this.storeTableNum &&
        this.cartSelectData.length > 1
      ) {
        this.$utils.toUrl(
          `/alipay-order/spellOrder/index?flag_id=${this.storeFlagId}&shareId=${this.startManId}`
        );
      }

      // 桌号点餐
      if (this.storeTableNum || this.cartSelectData.length <= 1) {
        let mch_info = {
          mch_id: 0,
          goods_list: [],
        };
        let arr = [];
        this.cartSelectData.forEach((d) => {
          d.goods_list.forEach((k) => {
            let item = {};
            item["food_cart_id"] = k.cart_id;
            arr.push(item);
          });
        });
        mch_info.goods_list = arr;
        let params = {
          mch_list: JSON.stringify([mch_info]),
          flag_id: this.storeFlagId,
          table_num: this.storeTableNum,
        };

        this.$utils.toUrl(
          `/alipay-order/order/order?order_info=${JSON.stringify(
            params
          )}&mealType=shop`
        );
      }
    },
  },
};
</script>

<style scoped lang="scss">
.component-box {
  width: 100%;
  position: relative;
  // z-index: 15;
  padding-bottom: 100rpx;

  .classify-section {
    width: 100%;
    .classify-header {
      width: 100%;
      position: relative;
    }
    .classify-body {
      padding-bottom: 2.67vw;
      position: relative;
      .classify-goods {
        width: 100%;
        height: 1px;
      }
    }
  }
  .flex-layout {
    position: relative;
    overflow: hidden;
    clear: both;
    .classify-header {
      width: 21.33vw;
      height: 100%;
      position: absolute !important;
      left: 0;
      top: 0;
      background-color: #ffffff;
    }
    .left-hold-place {
      width: 21.33vw;
      clear: both;
      float: left;
      padding-top: 20px;
      overflow: hidden;
      .tab-item {
        width: 100%;
        height: 12vw;
      }
    }
    .classify-body {
      width: 78.67vw;
      padding-top: 2.93vw;
      float: right;
    }
  }

  .module-bg {
    width: 100%;
    height: 100%;
    z-index: -1;
    position: absolute;
    left: 0;
    top: 0;
  }
}
</style>
